package test;


import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import net.rubyeye.xmemcached.MemcachedClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.Cache;
import org.springframework.cache.support.AbstractCacheManager;
import org.springframework.util.Assert;

import java.util.Collection;
import java.util.Map;

/**
 * Created by dws on 2018/3/29.
 */
public class XCacheManager extends AbstractCacheManager {

    private Map<String, Cache> cacheMap = Maps.newConcurrentMap();
    //namespace和过期时间的分隔符
    public static final String SEPARATOR = "#";

    private MemcachedClient client;

    @Value("${memcached.server}")
    private String memcachedServer;

    @Autowired
    public void setClient(MemcachedClient client) {
        Assert.notNull(client, "memcached client cannot be null");
        this.client = client;
    }

    @Override
    public Cache getCache(String name) {
        String[] split = name.split(SEPARATOR);

        String namespace = split[0];
        //有效时间
        int expire = split.length > 1 ? (Strings.isNullOrEmpty(split[1]) ? 0 : Integer.valueOf(split[1]).intValue()) : 0;
        //获取超时时间
        int timeout = split.length > 2 ? (Strings.isNullOrEmpty(split[1]) ? 0 : Integer.valueOf(split[2]).intValue()) : 0;

        Cache cache = cacheMap.get(namespace);
        if (cache == null) {
            cache = new XCache(namespace, expire, timeout, client, memcachedServer);
            cacheMap.put(namespace, cache);
        }
        return cache;
    }
    //    @Override
//    public Collection<String> getCacheNames() {
//        return cacheMap.keySet();
//    }
    @Override
    protected Collection<? extends Cache> loadCaches() {
        return cacheMap.values();
    }
}
